package com.nit.service.impl;

import com.nit.dto.GoodsDTO;
import com.nit.dto.utils.PaginationDTO;
import com.nit.dto.utils.TableRequestDTO;
import com.nit.dto.utils.TableResponseDTO;
import com.nit.entity.GoodsEntity;
import com.nit.mapper.GoodsMapper;
import com.nit.service.GoodsService;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import net.sf.json.JSONArray;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Resource
    private GoodsMapper goodsMapper;

    @Override
    public TableResponseDTO query(TableRequestDTO tableRequestDTO) throws Exception {

        Long count = goodsMapper.count4Table(
                tableRequestDTO.getJsonSearch().get("goodsName"),
                tableRequestDTO.getJsonSearch().get("goodsCate")
        );
        List<GoodsDTO> goodsDTOS = goodsMapper.list4Table(
                tableRequestDTO.getStart(count),
                tableRequestDTO.getPageSize(),
                tableRequestDTO.getJsonSearch().get("goodsName"),
                tableRequestDTO.getJsonSearch().get("goodsCate")
        );
        TableResponseDTO tableResponseDTO = new TableResponseDTO(goodsDTOS,
                new PaginationDTO(tableRequestDTO.getPageSize(),
                        count, tableRequestDTO.getCurrentPage(),
                        String.valueOf(tableRequestDTO.getSearch())));
        return tableResponseDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long add(GoodsDTO goodsDTO) throws Exception {
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        GoodsEntity goodsEntity = mapperFactory.getMapperFacade().map(goodsDTO, GoodsEntity.class);
        goodsEntity.setGmtCreate(new Date());
        goodsMapper.add(goodsEntity);
        return goodsEntity.getGoodsId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long remove(String goodsIds) throws Exception {
        JSONArray jsonArray = JSONArray.fromObject(goodsIds);
        for (int i = 0; i < jsonArray.size(); i++) {
            goodsMapper.remove(Long.parseLong(jsonArray.get(i).toString()));
        }
        return Long.parseLong(String.valueOf(jsonArray.size()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long update(GoodsDTO goodsDTO) throws Exception {
        return goodsMapper.update(goodsDTO).longValue();
    }
}
